﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScreenshotWindow;

internal class ScreenshotCanvas:Control
{
    // 存储完整屏幕截图，由外部传入
    public Bitmap? FullBitmap { get; set; }

    private Point? start;
    private Rect selection;

    public override void Render(DrawingContext context)
    {
        base.Render(context);

        if (FullBitmap != null)
        {
            // 绘制全屏背景
            var src = new Rect(0, 0, FullBitmap.PixelSize.Width, FullBitmap.PixelSize.Height);
            var dest = new Rect(0, 0, Bounds.Width, Bounds.Height);
            context.DrawImage(FullBitmap, src, dest);
        }

        // 半透明遮罩
        var overlayBrush = new SolidColorBrush(Colors.Black) { Opacity = 0.4 };
        context.FillRectangle(overlayBrush, new Rect(0, 0, Bounds.Width, Bounds.Height));

        // 绘制选区
        if (start.HasValue)
        {
            context.DrawRectangle(new Pen(new SolidColorBrush(Colors.LightBlue), 2), selection);
        }
    }

    protected override void OnPointerPressed(PointerPressedEventArgs e)
    {
        start = e.GetPosition(this);
        selection = new Rect(start.Value, start.Value);
        base.OnPointerPressed(e);
    }

    protected override void OnPointerMoved(PointerEventArgs e)
    {
        if (start.HasValue)
        {
            var pt = e.GetPosition(this);
            selection = new Rect(start.Value, pt);
            InvalidateVisual();
        }
        base.OnPointerMoved(e);
    }

    protected override void OnPointerReleased(PointerReleasedEventArgs e)
    {
        start = null;
        InvalidateVisual();
        base.OnPointerReleased(e);
    }

    // 根据选择区域裁剪 FullBitmap
    public Bitmap? Capture()
    {
        if (FullBitmap == null || selection.Width <= 0 || selection.Height <= 0)
            return null;

        var pixelSize = new PixelSize((int)selection.Width, (int)selection.Height);
        var rtb = new RenderTargetBitmap(pixelSize, new Vector(96, 96));
        // 手动绘制: 使用 DrawingContext
        using (var ctx = rtb.CreateDrawingContext())
        {
            // 平移到选区起始点
            ctx.PushTransform(Matrix.CreateTranslation(-selection.X, -selection.Y));
            // 绘制背景
            var src = new Rect(0, 0, FullBitmap.PixelSize.Width, FullBitmap.PixelSize.Height);
            var dest = new Rect(0, 0, Bounds.Width, Bounds.Height);
            ctx.DrawImage(FullBitmap, src, dest);
        }

        return rtb;
    }
}
